package com.yupi.yupicturebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.common.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.post.*;
import com.yupi.yupicturebackend.model.entity.Post;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.vo.PostVO;
import com.yupi.yupicturebackend.service.PostService;
import com.yupi.yupicturebackend.service.UserService;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.model.dto.picture.PictureUploadRequest;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import org.apache.commons.lang3.StringUtils;

import com.yupi.yupicturebackend.model.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 帖子接口
 */
@RestController
@RequestMapping("/post")
@Slf4j
@Api(tags = "帖子接口")
public class PostController {

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    // region 增删改查

    /**
     * 创建帖子（带图片上传）
     *
     * @param request HTTP请求
     * @return 新创建的帖子ID
     */
    @ApiOperation(value = "创建帖子（带图片上传）", notes = "创建新帖子并上传图片")
    @PostMapping("/add/with-picture")
    public BaseResponse<Long> addPostWithPicture(PostAddWithPictureRequest postRequest, HttpServletRequest request) {
        if (postRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 1. 处理图片上传（如果有）
        Long pictureId = null;
        MultipartFile pictureFile = postRequest.getPicture();
        if (pictureFile != null) {
            // 创建图片上传请求
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            
            // 上传图片
            PictureVO pictureVO = pictureService.uploadPicture(pictureFile, pictureUploadRequest, loginUser);
            if (pictureVO == null || pictureVO.getId() == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
            }
            
            // 更新图片标签
            Picture picture = new Picture();
            picture.setId(pictureVO.getId());
            picture.setTags(postRequest.getTags());
            picture.setUpdateTime(LocalDateTime.now().toDate());
            boolean updateResult = pictureService.updateById(picture);
            ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "图片标签更新失败");
            
            pictureId = pictureVO.getId();
        }
        
        // 2. 校验帖子参数
        String title = postRequest.getTitle();
        String content = postRequest.getContent();
        ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content), ErrorCode.PARAMS_ERROR);
        
        // 3. 创建帖子
        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setUserId(loginUser.getId());
        post.setPictureId(pictureId);  // 关联新上传的图片（如果有）
        
        boolean result = postService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        return ResultUtils.success(post.getId());
    }


    /**
     * 创建
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "创建帖子", notes = "创建一个新的帖子")
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        if(postAddRequest.getTitle() == null){
            postAddRequest.setTitle("");
        }
        BeanUtils.copyProperties(postAddRequest, post);
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());

        boolean result = postService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newPostId = post.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "删除帖子", notes = "根据id删除帖子")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postUpdateRequest
     * @return
     */
    @ApiOperation(value = "更新帖子", notes = "更新帖子信息（仅管理员）")
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest,
            HttpServletRequest request) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Post post = new Post();
        BeanUtils.copyProperties(postUpdateRequest, post);
        long id = postUpdateRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可修改
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取帖子详情", notes = "根据id获取帖子详情信息")
    @GetMapping("/get/vo")
    public BaseResponse<PostVO> getPostVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = postService.getById(id);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(postService.getPostVO(post, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "分页获取帖子列表", notes = "分页获取帖子列表信息")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
            HttpServletRequest request) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "获取我的帖子列表", notes = "分页获取当前用户创建的帖子列表")
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostVO>> listMyPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
            HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(loginUser.getId());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    // endregion
}
